var db = require("./db");

function time(date,s){
	var d=date.toJSON().substr(0,10);
	d=d.replace(/-/g,"/")+" "+s;
	return Number(new Date(d).getTime());
}

module.exports = {

	insertSession: function(param, callback) {
		var sql = "INSERT INTO `mmlink`.`t_session` ( `SESSION_ID`, `KEY_ID`, `JOBID`, `USER_ID`, `CHANNEL`, `CREATE_TIME`, `STATUS`, `START_TIME`, `END_TIME`,`SENDER`,`ACCEPTER`,`BUSINESS` ) VALUES ( ?, ?, ?, ?, ?, ?, 1, ?, NULL,?,?,?)";
		db.query({
			sql: sql,
			values: param
		}, callback);
	},

	insertMessage: function(param, callback) {
		var sql = "INSERT INTO `mmlink`.`t_message` ( `MESSAGE_ID`, `SESSION_ID`, `KEY_ID`, `SEND_TIME`, `TYPE`, `CONTENT`, `STATUS`,`NAME_FOR_MSG`,`IMAGE_FOR_MSG`,`SOURCE` ) VALUES (?, ?, ?, ?, ?, ?, ?,?,?,?)";
		db.query({
			sql: sql,
			values: param
		}, callback);
	},

	selectMessageBySessionId: function() {

	},

	updateSession: function(keys, values, sessionId, callback) {
		var sql = "UPDATE T_SESSION SET " + keys + "='" + values + "' WHERE SESSION_ID= '" + sessionId + "'";
		db.query({
			sql: sql,
			values: null
		}, callback);
	},

	querySession: function(param, callback) {
		var sql = "SELECT * FROM T_SESSION WHERE JOBID=? ORDER BY CREATE_TIME DESC";
		db.query({
			sql: sql,
			values: [param]
		}, function(value) {
			var data = {
				"total": value.length,
				"rows": value
			}
			callback && callback(data);
		})
	},
	
	insertSummary:function(param,callback){
		var sql="INSERT INTO `mmlink`.`t_summary` ( `UUID`, `SESSION_ID`, `KEY_ID`, `CREATE_TIME`, `SUBJECT`, `DESCR`, `SOLUTION`, `STATUS` ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
		db.query({
			sql: sql,
			values: param
		}, callback);
	},
	
	sessionReport:function(type,callback){
		var sql1="SELECT COUNT(T.SESSION_ID) COUNT, T.TIME LABEL FROM ( SELECT SESSION_ID, FROM_UNIXTIME( CREATE_TIME / 1000, '%m-%d %H' ) TIME FROM T_SESSION WHERE CREATE_TIME > ? AND CREATE_TIME < ? ) T GROUP BY T.TIME";
		var sql2="SELECT COUNT(SESSION_ID) COUNT,JOBID LABEL FROM T_SESSION WHERE CREATE_TIME > ? AND CREATE_TIME < ? GROUP BY JOBID";
		var sql3="SELECT COUNT(SESSION_ID) COUNT,IFNULL(BUSINESS,'其它') LABEL  FROM T_SESSION WHERE CREATE_TIME > ? AND CREATE_TIME < ? GROUP BY BUSINESS";
		var sql="";
		if(type=="h"){
			sql=sql1;
		}else if(type=="a"){
			sql=sql2;
		}else if(type=="b"){
			sql=sql3;
		}
		var p=[time(new Date(),"00:00:00"),time(new Date(),"23:59:59")];
		db.query({
			sql: sql,
			values: p,
		}, callback);
	},
	
	queryMessageBySessionId:function(param,callback){
		var sql="select SESSION_ID sessionId,KEY_ID keyId,SEND_TIME sendTime,TYPE type,CONTENT content,NAME_FOR_MSG name,IMAGE_FOR_MSG image,SOURCE source from t_message where SESSION_ID =? ORDER BY SEND_TIME desc";
		db.query({
			sql: sql,
			values: [param],
		}, callback);
	}
}